package com.ruoyi.file.config;

import java.net.URI;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.minio.MinioClient;

/**
 * Minio 配置信息
 *
 * @author ruoyi
 */
@Configuration
@ConditionalOnProperty(prefix = "minio", name = "url")
@ConfigurationProperties(prefix = "minio")
public class MinioConfig
{
    /**
     * 服务地址
     */
    private String url;

    /**
     * 用户名
     */
    private String accessKey;

    /**
     * 密码
     */
    private String secretKey;

    /**
     * 存储桶名称
     */
    private String bucketName;

    public String getUrl()
    {
        return url;
    }

    public void setUrl(String url)
    {
        this.url = url;
    }

    public String getAccessKey()
    {
        return accessKey;
    }

    public void setAccessKey(String accessKey)
    {
        this.accessKey = accessKey;
    }

    public String getSecretKey()
    {
        return secretKey;
    }

    public void setSecretKey(String secretKey)
    {
        this.secretKey = secretKey;
    }

    public String getBucketName()
    {
        return bucketName;
    }

    public void setBucketName(String bucketName)
    {
        this.bucketName = bucketName;
    }

    @Bean
    public MinioClient getMinioClient()
    {
        try
        {
            // 解析URL，提取主机名和端口
            String endpoint = url;
            if (endpoint == null || endpoint.isEmpty())
            {
                throw new IllegalArgumentException("MinIO URL 不能为空");
            }
            
            // 如果URL不包含协议，添加http://
            if (!endpoint.startsWith("http://") && !endpoint.startsWith("https://"))
            {
                endpoint = "http://" + endpoint;
            }
            
            // 使用URI解析，提取主机名和端口
            URI uri = new URI(endpoint);
            String host = uri.getHost();
            int port = uri.getPort();
            
            // 如果端口为-1（未指定），使用默认端口
            if (port == -1)
            {
                if ("https".equals(uri.getScheme()))
                {
                    port = 443;
                }
                else
                {
                    port = 9000; // MinIO默认端口
                }
            }
            
            // 构建MinioClient，使用主机名和端口
            MinioClient.Builder builder = MinioClient.builder()
                    .endpoint(host, port, "https".equals(uri.getScheme()))
                    .credentials(accessKey, secretKey);
            
            return builder.build();
        }
        catch (Exception e)
        {
            throw new IllegalArgumentException("MinIO URL 配置错误: " + url + ", 错误: " + e.getMessage(), e);
        }
    }
}
